package org.sith.taskrunner.gwt.server.services.user;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.sith.taskrunner.api.user.Role;
import org.sith.taskrunner.api.user.User;
import org.sith.taskrunner.ejb.db.entity.UserEntity;
import org.sith.taskrunner.ejb.services.UserManagerService;
import org.sith.taskrunner.gwt.client.services.user.UsersManageGWTService;
import org.sith.taskrunner.gwt.server.DBEntityTargetChecker;
import org.sith.taskrunner.gwt.server.ProxyConverter;
import org.sith.taskrunner.gwt.server.ProxyTargetChecker;
import org.sith.taskrunner.gwt.shared.proxy.RoleProxy;
import org.sith.taskrunner.gwt.shared.proxy.UserEntityProxy;

import javax.ejb.EJB;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: sith
 * Date: Oct 31, 2010
 * Time: 10:46:17 AM
 * To change this template use File | Settings | File Templates.
 */
public class UsersManageManageGWTServiceImpl extends RemoteServiceServlet implements UsersManageGWTService {

    @EJB(name = "UserManagerEJB")
    private UserManagerService usersManageService;

    private final DBEntityTargetChecker dbEntityTargetChecker = new DBEntityTargetChecker();
    private final ProxyTargetChecker proxyTargetChecker = new ProxyTargetChecker();
    private final ProxyConverter proxyConverter = new ProxyConverter();


    @Override
    public void addUser(UserEntityProxy user) {
        UserEntity userEntity = new UserEntity();
        proxyConverter.convert(user, userEntity, proxyTargetChecker);
        usersManageService.addUser(userEntity);

    }

    @Override
    public void removeUser(UserEntityProxy user) {
        usersManageService.removeUserById(user.getId());
    }

    @Override
    public void updateUser(UserEntityProxy user) {
        throw new IllegalStateException("Not implemente yet");
    }

    @Override
    public void updateUserActiveState(Long id, boolean active) {
        usersManageService.updateActiveState(id, active);

    }

    @Override
    public void updateUserRole(Long id, RoleProxy role) {
        Role roleEntity = Role.valueOf(role.name());

        usersManageService.updateRole(id, roleEntity);


    }

    @Override
    public UserEntityProxy getUser(Long id) {
        throw new IllegalStateException("Not implemented yet");
    }

    @Override
    public List<UserEntityProxy> getUsers() {
        List<? extends User> allUsers = usersManageService.getAllUsers();
        List<UserEntityProxy> proxies = new ArrayList<UserEntityProxy>();

        for (User allUser : allUsers) {
            UserEntityProxy proxy = new UserEntityProxy();
            proxyConverter.convert(allUser, proxy, dbEntityTargetChecker);
            proxies.add(proxy);

        }

        return proxies;
    }
}